package com.ccnu.demojava.mq.kafka;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;

import java.time.Duration;
import java.util.*;

public class RKafkaConsumer {
    public static void main(String[] args) throws Exception {
        String topicName = "kafka_topic";
        Properties props = new Properties();

        props.put("bootstrap.servers", "172.31.72.75:9092");
        props.put("group.id", "test");
        props.put("enable.auto.commit", "true");
        props.put("auto.commit.interval.ms", "1000");
        props.put("session.timeout.ms", "30000");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(props);

        //Kafka Consumer subscribes list of topics here.
        consumer.subscribe(Arrays.asList(topicName));
        List<PartitionInfo> partitions = consumer.partitionsFor(topicName);

        ArrayList<TopicPartition> tpArray = new ArrayList<>();
        for (int i=0; i<partitions.size(); i++) {
            tpArray.add(new TopicPartition(topicName, i));
        }

        consumer.assign(tpArray);
        // print the topic name
        System.out.println("Subscribed to topic " + topicName);
        int i = 0;
        Date startDT = new Date();
        System.out.println("timer:" + String.valueOf(startDT.getTime()));
        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
            for (ConsumerRecord<String, String> record : records) {
                // print the offset,key and value for the consumer records.
                System.out.printf("offset = %d, key = %s, value = %s\n", record.offset(), record.key(), record.value());
            }
            i++;

            if (i>1000000) {
                Date endDT = new Date();
                System.out.println("cost time:" + String.valueOf(endDT.getTime() - startDT.getTime()));
                return;
            }
        }
    }
}
